﻿using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using ST.Buz.Base;
using ST.Buz.Base.Entity;
using ST.Buz.Base.ViewModel;
using ST.Common.Data;
using ST.Common.Util;
using ST.Common.Util.Model;
using ST.Common.Util.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;

namespace ST.Buz.Service
{
	public partial interface IServiceSysUserBankCard
	{
		/// <summary>
		/// 获取分页数据
		/// </summary>
		/// <param name="pageNum"></param>
		/// <param name="pageSize"></param>
		/// <param name="code"></param>
		/// <returns></returns>
		PageData GetPageList(VMS_Sys_UserBankCard searchModel);

		/// <summary>
		/// 新增或修改当前用户的银行卡信息
		/// </summary>
		/// <param name="vm"></param>
		/// <param name="sessionCurrent"></param>
		/// <returns></returns>
		int AddOrUpdate(Sys_UserBankCard vm, UserSession sessionCurrent);

		/// <summary>
		/// 删除当前用户指定的银行卡
		/// </summary>
		/// <param name="id"></param>
		/// <param name="sessionCurrent"></param>
		/// <returns></returns>
		bool Delete(int id, UserSession sessionCurrent);
	}

	public partial class ServiceSysUserBankCard
	{
		private readonly IServiceSysLog serviceSysLog;

		public ServiceSysUserBankCard(BuzContext ctx,
			IServiceSysLog _serviceSysLog,
			ILogger<ServiceSysUserBankCard> log)
		{
			serviceSysLog = _serviceSysLog;

			context = ctx;
			logger = log;
		}

		private IQueryable<Sys_UserBankCard> GetQuery(VMS_Sys_UserBankCard searchModel)
		{
			var query = from m in context.SysUserBankCard select m;
			if (!string.IsNullOrEmpty(searchModel.name))
			{
				query = query.Where(m => EF.Functions.Like(m.AccountName, "%" + searchModel.name + "%"));
			}
			if (!string.IsNullOrEmpty(searchModel.mobile))
			{
				query = query.Where(m => m.UserMobile == searchModel.mobile);
			}
			if (searchModel.userid > 0)
			{
				query = query.Where(m => m.UserID == searchModel.userid);
			}
			return query;
		}

		/// <summary>
		/// 分页列表
		/// </summary>
		public PageData GetPageList(VMS_Sys_UserBankCard searchModel)
		{
			PageData result = null;
			try
			{
				searchModel.Validate();
				var query = GetQuery(searchModel);
				result = new PageData(searchModel.pnum.Value, searchModel.psize.Value);
				var lst = result.LoadQuery(query);
				if (searchModel.encrypt && lst != null && lst.Count > 0)
				{
					foreach (Sys_UserBankCard m in lst)
					{
						m.UserMobile = !string.IsNullOrEmpty(m.UserMobile) && m.UserMobile.Length > 7 ? m.UserMobile.Substring(0, 3) + "****" + m.UserMobile.Substring(m.UserMobile.Length - 4) : m.UserMobile;
					}
				}
				result.list = lst;
			}
			catch (BuzException ex)
			{
				throw ex;
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, "获取分页数据出错");
				throw new BuzException("获取分页数据失败，" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message));
			}
			return result;
		}

		public int GetCount(VMS_Sys_UserBankCard searchModel)
		{
			var query = GetQuery(searchModel);
			return query.Count();
		}

		/// <summary>
		/// 新增或修改当前用户的银行卡信息
		/// </summary>
		/// <param name="vm"></param>
		/// <param name="sessionCurrent"></param>
		/// <returns></returns>
		public int AddOrUpdate(Sys_UserBankCard vm, UserSession sessionCurrent)
		{
			try
			{
				if (vm == null)
				{
					throw new BuzException("参数不能为空");
				}
				DateTime dtNow = DateTime.Now;
				string ip = GetRequestIP();

				Sys_UserBankCard model = null;
				if (vm.ID > 0)
				{
					model = context.SysUserBankCard.SingleOrDefault(m => m.ID == vm.ID);
					if (model == null)
					{
						throw new BuzException("未找到相关信息");
					}
					serviceSysLog.Add(sessionCurrent, ip, $"修改当前用户指定的银行卡，原卡号：{model.AccountNo}，新卡号：{vm.AccountNo}", dtNow);

					model.LastModifyDate = dtNow;
					model.LastModifyManID = sessionCurrent.UserID;
					model.LastModifyManName = sessionCurrent.UserName;

					//todo:更新银行卡信息
				}
				else
				{
					vm.UserID = sessionCurrent.UserID;

					vm.AddDate = dtNow;
					vm.AddManID = sessionCurrent.UserID;
					vm.AddManName = sessionCurrent.UserName;
					vm.LastModifyDate = dtNow;
					vm.LastModifyManID = sessionCurrent.UserID;
					vm.LastModifyManName = sessionCurrent.UserName;

					context.SysUserBankCard.Add(model);
				}

				context.SaveChanges();

				return model.ID;
			}
			catch (BuzException ex)
			{
				throw ex;
			}
			catch (DbUpdateException ex)
			{
				logger.LogError(ex.InnerException ?? ex, "保存信息出错");
				throw new BuzException("保存失败，" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message));
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, "保存信息出错");
				throw new BuzException("保存失败，" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message));
			}
		}

		/// <summary>
		/// 删除当前用户指定的银行卡
		/// </summary>
		/// <param name="id"></param>
		/// <param name="sessionCurrent"></param>
		/// <returns></returns>
		public bool Delete(int id, UserSession sessionCurrent)
		{
			bool success = false;
			try
			{
				Sys_UserBankCard modelOld = context.SysUserBankCard.SingleOrDefault(m => m.ID == id);
				if (modelOld == null)
				{
					throw new BuzException("记录不存在");
				}
				if (modelOld.UserID != sessionCurrent.UserID)//非当前用户卡不能删除
				{
					throw new BuzException("此银行卡非当前用户所有");
				}

				Sys_Log log = new Sys_Log()
				{
					LogContent = $"删除当前用户指定的银行卡，原卡号：{modelOld.AccountNo}",
					LogManIP = GetRequestIP(),
					LogManID = sessionCurrent.UserID,
					LogManName = sessionCurrent.UserName,
					LogTime = DateTime.Now
				};
				context.SysLog.Add(log);

				context.SysUserBankCard.Remove(modelOld);
				context.SaveChanges();

				success = true;
			}
			catch (BuzException ex)
			{
				throw ex;
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, "删除对象信息出错");
				throw new BuzException("删除失败，" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message));
			}
			return success;
		}
	}
}